<template>
  <div class="production-issues-container">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="queryForm" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="业务系统">
              <el-input v-model="queryForm.business_system" placeholder="业务系统" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="问题描述">
              <el-input v-model="queryForm.issue_description" placeholder="问题描述" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发现人">
              <el-input v-model="queryForm.reporter" placeholder="发现人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 15px;">
          <el-col :span="6">
            <el-form-item label="解决状态">
              <el-select v-model="queryForm.status" placeholder="全部">
                <el-option label="待解决" value="待解决" />
                <el-option label="进行中" value="进行中" />
                <el-option label="已完成" value="已完成" />
                <el-option label="废弃" value="废弃" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间范围">
              <el-date-picker
                v-model="queryForm.create_time_range"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: right;">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <el-button type="primary" @click="showAddDialog" style="margin-bottom: 16px;">新增</el-button>
      <el-table v-loading="loading" :data="tableData" style="width: 100%" border :row-style="{ height: '40px' }" :cell-style="{ padding: '4px 0' }">
        <el-table-column prop="business_system" label="业务系统" />
        <el-table-column prop="issue_description" label="问题描述" width="200">
            <template #default="{ row }">
              <div style="height: 32px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" :title="row.issue_description">
                {{ row.issue_description }}
              </div>
            </template>
          </el-table-column>
        <el-table-column prop="issue_category" label="问题分类" />
        <el-table-column prop="impact_level" label="影响程度" />
        <el-table-column prop="reporter" label="发现人" />
        <el-table-column prop="developer" label="开发人员" />
        <el-table-column prop="tester" label="测试人员" />
        <el-table-column prop="status" label="解决状态" />
        <el-table-column prop="resolution_time" label="解决时间" width="180" />
        <el-table-column prop="root_cause" label="根本原因" width="150" />
        <el-table-column prop="solution" label="解决方案" width="150" />
        <el-table-column prop="remarks" label="备注" width="150" />
        <el-table-column prop="create_time" label="创建时间" width="180" />        
        <el-table-column prop="update_time" label="更新时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; text-align: right;"
      />
    </div>

    <!-- 对话框 -->
    <el-dialog v-model="showDialog" :title="dialogTitle" width="60%">
      <el-form :model="form" label-width="100px">
        <el-form-item label="业务系统" required>
          <el-input v-model="form.business_system" placeholder="请输入业务系统" />
        </el-form-item>
        <el-form-item label="问题描述" required>
          <WangEditor v-model="form.issue_description" height="300px" />
        </el-form-item>
        <el-form-item label="问题分类">
          <el-select v-model="form.issue_category" placeholder="请选择问题分类">
            <el-option label="功能性" value="功能性" />
            <el-option label="性能" value="性能" />
            <el-option label="安全" value="安全" />
            <el-option label="界面" value="界面" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="影响程度">
          <el-select v-model="form.impact_level" placeholder="请选择影响程度">
            <el-option label="严重" value="严重" />
            <el-option label="重大" value="重大" />
            <el-option label="一般" value="一般" />
            <el-option label="轻微" value="轻微" />
          </el-select>
        </el-form-item>
        <el-form-item label="发现人" required>
          <el-input v-model="form.reporter" placeholder="请输入发现人" />
        </el-form-item>
        <el-form-item label="开发人员">
          <el-input v-model="form.developer" placeholder="请输入开发人员" />
        </el-form-item>
        <el-form-item label="测试人员">
          <el-input v-model="form.tester" placeholder="请输入测试人员" />
        </el-form-item>
        <el-form-item label="解决状态">
          <el-select v-model="form.status" placeholder="请选择解决状态">
            <el-option label="待解决" value="待解决" />
            <el-option label="进行中" value="进行中" />
            <el-option label="已完成" value="已完成" />
            <el-option label="废弃" value="废弃" />
          </el-select>
        </el-form-item>
        <el-form-item label="根本原因">
          <el-input type="textarea" v-model="form.root_cause" placeholder="请输入根本原因" :rows="2" />
        </el-form-item>
        <el-form-item label="解决方案">
          <el-input type="textarea" v-model="form.solution" placeholder="请输入解决方案" :rows="2" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="form.remarks" placeholder="请输入备注" :rows="2" />
        </el-form-item>
        <el-form-item label="解决时间">
          <el-date-picker
            v-model="form.resolution_time"
            type="datetime"
            placeholder="请选择解决时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { apiGet, apiPost, apiPatch, apiDelete } from '@/request/apiUtils';
import type { ProductionIssue } from './types';
import WangEditor from '@/components/WangEditor.vue';
interface ProductionIssue {
  id?: number;
  business_system: string;
  issue_description: string;
  issue_category?: string | null;
  impact_level?: string | null;
  reporter: string;
  developer?: string | null;
  tester?: string | null;
  status: string; // 修正为字符串类型，与后端保持一致
  resolution_time?: string | null;
  root_cause?: string | null;
  solution?: string | null;
  remarks?: string | null;
  create_time?: string;
  update_time?: string;
}

// API响应接口，包含分页信息
interface ApiResponse {
  results: ProductionIssue[];
  count: number;
  next?: string | null;
  previous?: string | null;
  current_page_num?: number;
  total_pages?: number;
}

// 状态
const loading = ref(false);
const showDialog = ref(false);
const isCreate = ref(false);
const tableData = ref<ProductionIssue[]>([]);
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 路由
const router = useRouter();

// 表单数据
const queryForm = reactive({
  business_system: '',
  issue_description: '',
  reporter: '',
  status: '', // 解决状态筛选
  create_time_range: [] // 创建时间范围 [开始时间, 结束时间]
});
const form = reactive({
    business_system: '',
    issue_description: '',
    issue_category: null,
    impact_level: null,
    reporter: '',
    developer: null,
    tester: null,
    status: '待解决', // 修改为字符串类型，与后端一致
    resolution_time: null,
    root_cause: null,
    solution: null,
    remarks: null,
    id: undefined
  });

// 计算属性
const dialogTitle = computed(() => isCreate.value ? '新增生产问题' : '编辑生产问题');

// 初始数据加载
const loadData = async () => {
  loading.value = true;
  try {
    // 构建查询参数，预先定义所有可能的属性以避免TypeScript类型错误
    const params: {
      page: number;
      page_size: number;
      business_system: string;
      issue_description: string;
      reporter: string;
      status: string;
      create_time_start?: string;
      create_time_end?: string;
    } = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      business_system: queryForm.business_system,
      issue_description: queryForm.issue_description,
      reporter: queryForm.reporter,
      status: queryForm.status
    };
    
    // 处理时间范围参数
    if (queryForm.create_time_range && queryForm.create_time_range.length === 2) {
      params.create_time_start = queryForm.create_time_range[0];
      params.create_time_end = queryForm.create_time_range[1];
    }
    
    // 直接处理apiGet返回的数据
    // apiGet通过axios拦截器已经返回response.data
    const apiResponse = await apiGet('/api/production_issues/', params);
    
    // 数据验证和类型安全处理
    if (!apiResponse || typeof apiResponse !== 'object') {
      ElMessage.warning('未返回有效数据');
      tableData.value = [];
      pagination.total = 0;
      return;
    }
    
    // 按照TypeScript推荐的方式进行类型转换：先转换为unknown，再转换为ApiResponse
    const typedResponse = apiResponse as unknown as ApiResponse;
    
    // 安全获取和处理results数组
    const results = Array.isArray(typedResponse.results) 
      ? typedResponse.results 
      : [];
    
    // 确保每个item都符合ProductionIssue接口，特别是status字段
    tableData.value = results
      .filter(item => item && typeof item === 'object') // 过滤无效项
      .map(item => {
        // 创建符合ProductionIssue接口的对象
        return {
          // 确保必填字段存在
          id: item.id,
          business_system: String(item.business_system || ''),
          issue_description: String(item.issue_description || ''),
          reporter: String(item.reporter || ''),
          // 确保status字段始终为字符串
          status: String(item.status || '待解决'),
          // 可选字段
          issue_category: item.issue_category || null,
          impact_level: item.impact_level || null,
          developer: item.developer || null,
          tester: item.tester || null,
          resolution_time: item.resolution_time || null,
          root_cause: item.root_cause || null,
          solution: item.solution || null,
          remarks: item.remarks || null,
          // 确保时间字段正确处理
          create_time: item.create_time ? String(item.create_time) : '',
          update_time: item.update_time ? String(item.update_time) : ''
        };
      });
    
    // 安全设置分页总数
    pagination.total = typeof typedResponse.count === 'number' 
      ? typedResponse.count 
      : 0;

  } catch (error) {
    console.error('加载数据错误:', error);
    // 即使出错也设置空数组，避免表格显示异常
    tableData.value = [];
    pagination.total = 0;
    ElMessage.error('加载失败');
  } finally {
    loading.value = false;
  }
};

// 显示新增对话框
const showAddDialog = () => {
  isCreate.value = true;
  Object.assign(form, {
    business_system: '',
    issue_description: '',
    issue_category: null,
    impact_level: null,
    reporter: '',
    developer: null,
    tester: null,
    status: '待解决',
    resolution_time: null,
    root_cause: null,
    solution: null,
    remarks: null,
    id: undefined
  });
  showDialog.value = true;
};

// 显示编辑对话框
const showEditDialog = (row: ProductionIssue) => {
  isCreate.value = false;
  // 清理问题描述中的blob URL
  const cleanedRow = {
    ...row,
    issue_description: row.issue_description ? row.issue_description.replace(/blob:[^"']*/g, '') : ''
  };
  Object.assign(form, cleanedRow);
  showDialog.value = true;
};

// 确认提交
const handleConfirm = async () => {
  try {
    // 验证必填字段
    if (!form.business_system) {
      ElMessage.warning('请填写业务系统');
      return;
    }
    if (!form.issue_description) {
      ElMessage.warning('请填写问题描述');
      return;
    }
    if (!form.reporter) {
      ElMessage.warning('请填写发现人');
      return;
    }

    // 构造提交数据
    const submitData = {
      business_system: form.business_system,
      issue_description: form.issue_description,
      issue_category: form.issue_category,
      impact_level: form.impact_level,
      reporter: form.reporter,
      developer: form.developer,
      tester: form.tester,
      // 直接使用字符串形式的status值，保持与后端一致
      status: form.status || '待解决',
      resolution_time: form.resolution_time,
      root_cause: form.root_cause,
      solution: form.solution,
      remarks: form.remarks
    };

    if (isCreate.value) {
      await apiPost('/api/production_issues/', submitData);
      ElMessage.success('新增成功');
    } else {
      await apiPatch(`/api/production_issues/${form.id}/`, submitData);
      ElMessage.success('修改成功');
    }

    showDialog.value = false;
    loadData();
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error(isCreate.value ? '新增失败' : '修改失败');
  }
};


// 删除
const handleDelete = async (row: ProductionIssue) => {
  try {
    await ElMessageBox.confirm('确定删除？', '确认', {
      type: 'warning'
    });
    await apiDelete(`/api/production_issues/${row.id}/`);
    ElMessage.success('删除成功');
    loadData();
  } catch (error) {
    // 忽略取消操作
  }
};

  // 搜索
  const handleSearch = () => {
    pagination.currentPage = 1;
    loadData();
  };

  // 重置
  const handleReset = () => {
    queryForm.business_system = '';
    queryForm.issue_description = '';
    queryForm.reporter = '';
    queryForm.status = '';
    queryForm.create_time_range = [];
    handleSearch();
  };

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  loadData();
};

const handleCurrentChange = (current: number) => {
  pagination.currentPage = current;
  loadData();
};

  // 页面加载时获取数据
  onMounted(() => {
    loadData();
  });
</script>

<style scoped>
.production-issues-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.search-form, .table-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}
</style>